//
//  SearchViewController.m
//  LCOnePsychology
//
//  Created by li cheng on 16/8/31.
//  Copyright © 2016年 li cheng. All rights reserved.
//

#import "SearchViewController.h"
#import "Masonry.h"
#import "BaseCollectionView.h"
#import <AVFoundation/AVFoundation.h>
#import "MJMacro.h"
#import "CVCellOfSearchLabel.h"
#import "LCWaterFlowLayout.h"
#import "ZWYNetTool.h"
// 热门搜索的 model
#import "RootClassOfSearchChoice.h"
#import "DataOfSearchChoice.h"
#import "DataOfNeedSearchChoice.h"
#import "BaseTableView.h"
#import "TVCellOfSearchResult.h"
// 点击热门搜索的 model
#import "RootClassOfSearchResultModel.h"
#import "DataOfSearchResultModel.h"
#import "ArticleOfDataSearchResultModel.h"
// 自己输入搜索的 model
#import "ListOfDataSecondSearchResult.h"
#import "DataOfSecondSearchResult.h"
#import "RootClassOfSecondSearchResult.h"
// 这个 cell 之前阅读写的, 一样就拿来用了
#import "TVCellOfReadAriticle.h"
#import "UIImageView+WebCache.h"
#import "VCOfReadWeb.h"
@interface SearchViewController ()<UISearchBarDelegate, UICollectionViewDelegate, UICollectionViewDataSource, LCWaterFlowLayoutDelegate, UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) NSArray *arrayOfTitle;
@property (nonatomic, strong) BaseCollectionView *CVOfHotSearch;
@property (nonatomic, strong) LCWaterFlowLayout *layout;
@property (nonatomic, strong) RootClassOfSearchChoice *rootClassOfSearchChoice;
@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, strong) BaseTableView *tableViewOfSearchResult;
@property (nonatomic, strong) RootClassOfSearchResultModel *rootClassOfSearchResultModel;
@property (nonatomic, strong) BaseTableView *secondTableView;
@property (nonatomic, strong) RootClassOfSecondSearchResult *rootClassOfSecondSearchResult;
@end

@implementation SearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    // 数据解析
    [self handleData];
    self.view.backgroundColor = [UIColor whiteColor];
    // 创建上面的搜索栏
    [self createSearchBar];
    // 创建下面的热门搜索的 button 按钮
    [self createHotSearchButton];
    // 创建 tableView
    [self creatTabelView];
    // 创建 第二个 tableView
    [self createSecondTableView];
}
#pragma mark - 数据解析
- (void)handleData{
    [ZWYNetTool GET:@"http://yiapi.xinli001.com/v2/yi/search-hot-key.json?key=18ee0593a01c07f71d28fa936d671457&_platform=ios&_version=4.0" andBody:nil andHeader:nil andResponse:ZWYJSON andSuccessBlock:^(id result) {
        _rootClassOfSearchChoice = [RootClassOfSearchChoice modelDic:result];
        self.layout.numberOfRow = 0.0f;
        self.layout.numberOfitemInRow = 0.0f;
        self.layout.contentWidth = 0.0f;
        [self.CVOfHotSearch reloadData];
    } andFailureBlock:^(NSError *error) {
        
    }];
}
#pragma mark - searchBar 的方法, 获取输入的文字
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText;{
    if ([searchText  isEqual: @""]) {
        self.tableViewOfSearchResult.frame = CGRectMake(-SCREEN_WIDTH, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64);
         _secondTableView.frame = CGRectMake(SCREEN_WIDTH * 2, 0,SCREEN_WIDTH, SCREEN_WIDTH - 64);
    } else {
        [ZWYNetTool POST:@"http://yiapi.xinli001.com/v2/yi/get-search-list.json?key=18ee0593a01c07f71d28fa936d671457&_platform=ios&_version=4.0" andBody:[NSString stringWithFormat:@"{\"limit\":\"10\",\"searchword\":\"%@\"}", searchText] andBodyStyle:ZWYBodyString andHeader:@{@"Content-Type":@"application/json"} andResponse:ZWYJSON andSuccessBlock:^(id result) {
            _rootClassOfSecondSearchResult = [RootClassOfSecondSearchResult modelDic:result];
            if ([_rootClassOfSecondSearchResult.message isEqualToString:@"获取成功"]) {
                _secondTableView.frame = CGRectMake(0, 0,SCREEN_WIDTH, SCREEN_WIDTH - 64);
            }
            [self.secondTableView reloadData];
        } andFailureBlock:^(NSError *error) {
            
        }];
    }
}
#pragma mark - 创建searchBar
- (void)createSearchBar{
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 150, 20)];
    self.navigationItem.titleView = _searchBar;
    self.searchBar.placeholder = @"输入专家姓名、问题关键字";
    self.searchBar.showsCancelButton = YES;
    self.searchBar.delegate = self;
    // 成为第一响应者
    [self.searchBar becomeFirstResponder];
    
}
#pragma mark - 创建 tabelView
- (void)creatTabelView{
    self.tableViewOfSearchResult = [[BaseTableView alloc] initWithFrame:CGRectMake(-SCREEN_WIDTH, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64) style:UITableViewStylePlain];
    self.tableViewOfSearchResult.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_tableViewOfSearchResult];
    self.tableViewOfSearchResult.delegate = self;
    self.tableViewOfSearchResult.dataSource = self;
    [self.tableViewOfSearchResult registerNib:[UINib nibWithNibName:@"TVCellOfReadAriticle" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"TVCellOfReadAriticle"];
}
#pragma mark - 还得再穿件一个 tabeleView
- (void)createSecondTableView{
    self.secondTableView = [[BaseTableView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH * 2, 0,SCREEN_WIDTH, SCREEN_WIDTH - 64) style:UITableViewStylePlain];
    self.secondTableView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_secondTableView];
    self.secondTableView.delegate = self;
    self.secondTableView.dataSource = self;
    [self.secondTableView registerNib:[UINib nibWithNibName:@"TVCellOfReadAriticle" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"TVCellOfReadAriticle"];
    [self.secondTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"];
}
#pragma mark - tableView 代理方法 row 的数量的确定
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if ([tableView isEqual:_tableViewOfSearchResult]) {
        NSLog(@"范德萨发的所发生的发的所发生的发大水发松岛枫");
        return _rootClassOfSearchResultModel.data.article.count;
    } else {
        return _rootClassOfSecondSearchResult.data.list.count;
    }
}
#pragma mark - 返回每个 row 的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([tableView isEqual:_tableViewOfSearchResult]) {
        return SCREEN_HEIGHT / 6;
    } else {
        return 44;
    }
}
#pragma mark - 分区头
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if ([tableView isEqual:_tableViewOfSearchResult]) {
        return [NSString stringWithFormat:@"相关文章(%ld)", _rootClassOfSearchResultModel.data.article.count];
    } else {
        return nil;
    }
}
#pragma mark - tableView 的点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([tableView isEqual:_secondTableView]) {
        self.secondTableView.frame = CGRectMake(SCREEN_WIDTH * 2, 0,SCREEN_WIDTH, SCREEN_WIDTH - 64);
        self.tableViewOfSearchResult.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64) ;
        self.searchBar.text = _rootClassOfSecondSearchResult.data.list[indexPath.row].name;
        [ZWYNetTool GET:[NSString stringWithFormat:@"http://yiapi.xinli001.com/v2/yi/get-hot-result?key=18ee0593a01c07f71d28fa936d671457&_platform=ios&_version=4.0&keyword=%@&page=1&size=10", _rootClassOfSecondSearchResult.data.list[indexPath.row].name] andBody:nil andHeader:nil andResponse:ZWYJSON andSuccessBlock:^(id result) {
            NSLog(@"%@", result);
            _rootClassOfSearchResultModel = [RootClassOfSearchResultModel modelDic:result];
            [self.tableViewOfSearchResult reloadData];
        } andFailureBlock:^(NSError *error) {
            
        }];
        // 放弃第一响应
        [self.searchBar resignFirstResponder];
    }
    if ([tableView isEqual:_tableViewOfSearchResult]) {
        NSLog(@"点我了");
        VCOfReadWeb *vcOfReadWeb = [[VCOfReadWeb alloc] init];
        UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:vcOfReadWeb];
        vcOfReadWeb.stringURL = [NSString stringWithFormat:@"http://yiapi.xinli001.com/v2/yi/article-detail-newpage/%@?user_id=1004358517&_version=4.0", _rootClassOfSearchResultModel.data.article[indexPath.row].article_id];
        
        vcOfReadWeb.myID = _rootClassOfSearchResultModel.data.article[indexPath.row].article_id;
//        _rootClassOfSearchResultModel.data.article[indexPath.row].article_id;
        [self presentViewController:navi animated:YES completion:^{
            
        }];

    }
}
#pragma mark - tabelView 代理方法 cell 的赋值
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([tableView isEqual:_tableViewOfSearchResult]) {
        TVCellOfReadAriticle *cell = [tableView dequeueReusableCellWithIdentifier:@"TVCellOfReadAriticle" forIndexPath:indexPath];
        [cell.myImageView sd_setImageWithURL:[NSURL URLWithString:_rootClassOfSearchResultModel.data.article[indexPath.row].img_url] placeholderImage:[UIImage imageNamed:@"JustAMoment"]];
        cell.titleLabel.text = _rootClassOfSearchResultModel.data.article[indexPath.row].title;
        cell.authorLabel.text = _rootClassOfSearchResultModel.data.article[indexPath.row].author;
        cell.viewnumLabel.text = _rootClassOfSearchResultModel.data.article[indexPath.row].viewnum;
        return cell;
    } else {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell" forIndexPath:indexPath];
        cell.imageView.image = [UIImage imageNamed:@"Search_16"];
        cell.textLabel.text = _rootClassOfSecondSearchResult.data.list[indexPath.row].name;
        return cell;
    }
}
#pragma mark - 按钮点击方法
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
#pragma mark - 创建热门搜索
- (void)createHotSearchButton{
    UIView *viewBlue = [[UIView alloc] initWithFrame:CGRectMake(10, 20, 3, 20)];
    viewBlue.backgroundColor = [UIColor blueColor];
    [self.view addSubview:viewBlue];
    UILabel *labelOfHotSearch = [[UILabel alloc] init];
    [self.view addSubview:labelOfHotSearch];
    labelOfHotSearch.text = @"热门搜索";
    [labelOfHotSearch mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(viewBlue).offset(5);
        make.centerY.mas_equalTo(viewBlue.mas_centerY);
        make.height.mas_equalTo(viewBlue.mas_height);
        make.width.mas_equalTo(100);
    }];
    // 创建下面的热门推荐的选项
    self.layout = [[LCWaterFlowLayout alloc] init];
    self.layout.delegate = self;
    self.CVOfHotSearch = [[BaseCollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:_layout];
    self.CVOfHotSearch.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.CVOfHotSearch];
    [self.CVOfHotSearch mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(labelOfHotSearch.mas_bottom).offset(20);
        make.left.equalTo(self.view).offset(20);
        make.width.mas_equalTo(self.view.bounds.size.width - 40);
        make.height.mas_equalTo(self.view.bounds.size.height / 3);
    }];
    self.CVOfHotSearch.delegate = self;
    self.CVOfHotSearch.dataSource = self;
    [self.CVOfHotSearch registerClass:[CVCellOfSearchLabel class] forCellWithReuseIdentifier:@"CVCellOfSearchLabel"];
}

#pragma mark - item 的数量
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return  _rootClassOfSearchChoice.data.data.count;
}
#pragma mark - CollectView cell 的赋值
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    CVCellOfSearchLabel *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CVCellOfSearchLabel" forIndexPath:indexPath];
    // reload 重新 cell fram 赋值
    cell.backgroundColor = [UIColor whiteColor];
    cell.frame = _layout.attributesArray[indexPath.row].frame;
    cell.labelOfSearch.frame = cell.bounds;
    cell.labelOfSearch.text = [NSString stringWithFormat:@"%@", _rootClassOfSearchChoice.data.data[indexPath.row].tag_name];
    cell.labelOfSearch.layer.cornerRadius = 10;
    cell.labelOfSearch.textAlignment = 1;
    cell.labelOfSearch.layer.borderWidth = 0.5;
    return cell;
}
#pragma mark - 自己写的 layout 代理方法
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout height:(CGFloat)height widthForItemAtIndexPath:(NSIndexPath *)indexPath{
    CGRect newRect = [_rootClassOfSearchChoice.data.data[indexPath.row].tag_name boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, 40) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName :[UIFont systemFontOfSize:17]} context:nil];
    return newRect.size.width;
}
#pragma mark - collectionView item 被点击的方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"%ld", (long)indexPath.row);
    
    self.tableViewOfSearchResult.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64) ;
    self.searchBar.text = _rootClassOfSearchChoice.data.data[indexPath.row].tag_name;
    [ZWYNetTool GET:[NSString stringWithFormat:@"http://yiapi.xinli001.com/v2/yi/get-hot-result?key=18ee0593a01c07f71d28fa936d671457&_platform=ios&_version=4.0&keyword=%@&page=1&size=10", _rootClassOfSearchChoice.data.data[indexPath.row].tag_name] andBody:nil andHeader:nil andResponse:ZWYJSON andSuccessBlock:^(id result) {
        NSLog(@"%@", result);
        _rootClassOfSearchResultModel = [RootClassOfSearchResultModel modelDic:result];
        [self.tableViewOfSearchResult reloadData];
    } andFailureBlock:^(NSError *error) {

    }];
    // 放弃第一响应
   [self.searchBar resignFirstResponder];
}

#pragma mark - 其他
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end



